package com.dajingling.dao.impl;

import com.dajingling.dao.BaseAdminDao;
import com.dajingling.util.DruidUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

public class AdminDaoMysql implements BaseAdminDao {
    private static final String SQL_UPDATE_LOGIN_TIME = "update eadmin set logintime=?,loginip=? where username=?";
    private static final String SQL_LOGIN = "select eid from eadmin where username=? and password=?";
    /**
     * 根据用户名，更新登录时间和登录ip
     *
     * @param username
     * @param date
     * @param ip
     */
    @Override
    public void updateLoginTime(String username, Date date, String ip) {
        //1.获取连接
        Connection connection = DruidUtil.getConnection();
        //2.预编译sql语句
        PreparedStatement statement = null;
        try {
            statement = connection.prepareStatement(SQL_UPDATE_LOGIN_TIME);
            statement.setDate(1,new java.sql.Date(date.getTime()));
            statement.setString(2,ip);
            statement.setString(3,username);
            statement.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(connection,statement,null);
        }
    }

    /**
     * 管理员根据账号密码登录
     *
     * @param username
     * @param password
     * @return
     */
    @Override
    public boolean login(String username, String password) {
        //1.获取连接
        Connection connection = DruidUtil.getConnection();
        //2.预编译sql语句
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            statement = connection.prepareStatement(SQL_LOGIN);
            //3.填充参数
            statement.setString(1,username);
            statement.setString(2,password);
            //4.执行获取结果集
            resultSet = statement.executeQuery();
            //5.查结果，返回
            return resultSet.next();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            //6.释放资源
            DruidUtil.close(connection,statement,resultSet);
        }
        return false;
    }
}
